package com.arpa.oms.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.oms.domain.dto.OmsPurchaseReturnDTO;
import com.arpa.oms.domain.entity.OmsPurchaseReturn;
import com.arpa.oms.domain.enums.OrderStatusEnum;
import com.arpa.oms.domain.vo.OmsPurchaseReturnVO;
import com.arpa.oms.domain.vo.OmsSaleReturnVO;
import com.arpa.oms.service.IOmsPurchaseReturnService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * OMS采购退货单 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-11-17
 */
@Api(tags = "OMS采购退货单")
@RestController
@RequestMapping(value="/omsPurchaseReturn", produces = "application/json;charset=UTF-8")
@Log4j2(topic = "business")
public class OmsPurchaseReturnController {

   @Autowired
   private IOmsPurchaseReturnService  iOmsPurchaseReturnService;

    /**
     * 获取 OMS采购退货单 列表
     *
     * @param omsPurchaseReturnDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 OMS采购退货单 列表", notes = "获取 OMS采购退货单 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsPurchaseReturnVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(OmsPurchaseReturnDTO omsPurchaseReturnDTO,HttpServletRequest request) {
        try {
            omsPurchaseReturnDTO.setGroupCode(UserUtil.getBranchCode());
            omsPurchaseReturnDTO.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            omsPurchaseReturnDTO.setWarehouseCodes(UserUtil.getShipmentAuthorizeWarehouseCodes());
            OmsPurchaseReturnVO omsPurchaseReturnVOSum = iOmsPurchaseReturnService.queryListSum(omsPurchaseReturnDTO);
            List<OmsPurchaseReturnVO> omsPurchaseReturnVOList = iOmsPurchaseReturnService.queryList(omsPurchaseReturnDTO);

            Page returnPage = new Page(omsPurchaseReturnDTO.getPageNum(),omsPurchaseReturnDTO.getPageSize());
            returnPage.setRecords(omsPurchaseReturnVOList);
            returnPage.setTotal(omsPurchaseReturnVOSum.getTotal());
            returnPage.setSumObject(omsPurchaseReturnVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 OMS采购退货单
     *
     * @param entity OmsPurchaseReturn
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 OMS采购退货单 ", notes = "添加 OMS采购退货单 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@RequestBody @Valid  OmsPurchaseReturn entity, HttpServletRequest request) {
        try {
            if (IterUtil.isEmpty(entity.getOmsPurchaseReturnItemList())) {
                return Result.error("新增采购退货单失败，退货商品为空！");
            }
            entity.setShipmentCode(UserUtil.getShipmentCompanyCode());
            entity.setShipmentName(UserUtil.getShipmentCompanyName());
            iOmsPurchaseReturnService.create(entity);
            return Result.ok("保存成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
    @ApiOperation(value = "提交采购单退货单 ", notes = "提交采购单退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String",
                    defaultValue = "Bearer 123456")
    })
    @NeedLogin
    @PostMapping("/submit")
    public Result submit(@RequestBody @Valid OmsPurchaseReturn entity, HttpServletRequest request) {
        try {
            if (IterUtil.isEmpty(entity.getOmsPurchaseReturnItemList())) {
                return Result.error("保存采购单退货单失败，采购退单商品为空！");
            }
            entity.setShipmentCode(UserUtil.getShipmentCompanyCode());
            entity.setShipmentName(UserUtil.getShipmentCompanyName());
            iOmsPurchaseReturnService.submit(entity);
            return Result.ok("提交成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    @ApiOperation(value = "作废采购退货单", notes = "作废采购退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "code", value = "采购单号", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @GetMapping(value = "/annul/{code}")
    public Result annul(@PathVariable String code, HttpServletRequest request) {
        try {
            iOmsPurchaseReturnService.annul(code);
            return Result.ok("作废成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取OMS采购退货单详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取OMS采购退货单详情", notes = "获取OMS采购退货单详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "OMS采购退货单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsPurchaseReturn.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result omsPurchaseReturn(@PathVariable String code, HttpServletRequest request) {
        try {
             OmsPurchaseReturnVO entity = iOmsPurchaseReturnService.getByCode(code);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 采购单审核
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "采购单审核", notes = "采购单审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "code", value = "采购退货单号", paramType = "path", dataType = "String", required = true),
            @ApiImplicitParam(name = "status", value = "审核结果：PASS/NO_PASS 大写", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "opinion", value = "审核意见", paramType = "query", dataType = "String"),
    })
    @NeedLogin
    @GetMapping(value = "/verify/{code}")
    public Result verify(@PathVariable String code, String status, @RequestParam(required = false) String opinion, HttpServletRequest request) {
        try {

            iOmsPurchaseReturnService.verify(code, status, opinion);
            return Result.ok("审核成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 删除 OMS采购退货单
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 OMS采购退货单 ", notes = "删除 OMS采购退货单 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iOmsPurchaseReturnService.remove(new QueryWrapper<OmsPurchaseReturn>().lambda().in(OmsPurchaseReturn::getCode,codes));
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 获取 OMS采购单 审核列表
     *
     * @param dto
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 OMS采购单退货 审核列表", notes = "获取 OMS采购单退货 审核列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsSaleReturnVO.class))
    @NeedLogin
    @GetMapping("/auditList")
    public Result auditList(OmsPurchaseReturnDTO omsPurchaseReturnDTO, HttpServletRequest request) {
        try {
            omsPurchaseReturnDTO.setGroupCode(UserUtil.getBranchCode());
            omsPurchaseReturnDTO.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            omsPurchaseReturnDTO.setWarehouseCodes(UserUtil.getShipmentAuthorizeWarehouseCodes());
            if (StrUtil.isBlank(omsPurchaseReturnDTO.getAuditStatus())) {
                List<String> auditStatus = Arrays.asList(OrderStatusEnum.PENDING.getValue(), OrderStatusEnum.NO_PASS.getValue(), OrderStatusEnum.PASS.getValue());
                String auditStatusStr = auditStatus.stream().map(c -> StrUtil.wrap(c, "'")).collect(Collectors.joining(","));
                omsPurchaseReturnDTO.setAuditStatus(auditStatusStr);
            }

            OmsPurchaseReturnVO omsPurchaseReturnVOSum = iOmsPurchaseReturnService.queryListSum(omsPurchaseReturnDTO);
            List<OmsPurchaseReturnVO> omsPurchaseReturnVOList = iOmsPurchaseReturnService.queryList(omsPurchaseReturnDTO);

            Page returnPage = new Page(omsPurchaseReturnDTO.getPageNum(),omsPurchaseReturnDTO.getPageSize());
            returnPage.setRecords(omsPurchaseReturnVOList);
            returnPage.setTotal(omsPurchaseReturnVOSum.getTotal());
            returnPage.setSumObject(omsPurchaseReturnVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }






 }
